package middleware

import (
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
)

// GetCurrentMember 获取当前登录的会员信息
// GetCurrentAdmin 获取当前登录的管理员信息
func GetCurrentMember(ctx *context.Context) (*models.Member, error) {
	// 从上下文中获取用户ID
	userId, ok := ctx.Input.GetData("user_id").(int64)
	if !ok {
		return nil, nil
	}

	// 从上下文中获取加盟商ID
	franchiseId, _ := ctx.Input.GetData("franchise_id").(int64)

	// 获取会员信息
	return models.GetMemberById(userId, franchiseId)
}

// MemberAuthMiddleware 会员认证中间件
func MemberAuthMiddleware() {
	web.InsertFilter("/api/v1/member/*", web.BeforeRouter, func(ctx *context.Context) {
		member, err := GetCurrentMember(ctx)
		if err != nil || member == nil {
			ctx.Output.JSON(map[string]interface{}{
				"success": false,
				"message": "未授权访问",
				"code":    401,
			}, true, false)
			return
		}
	})
}
